package top.dotgo.web.base.config.security;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.filter.GenericFilterBean;
import top.dotgo.kit.Const;
import top.dotgo.kit.ContextKit;
import top.dotgo.web.base.kit.JwtKit;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jornl
 * @date 2020/2/24 18:53 星期一
 */
public class SecurityFilter extends GenericFilterBean {
    public static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json;charset=UTF-8";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("UTF-8");
        response.setContentType(APPLICATION_JSON_CHARSET_UTF_8);
        response.setCharacterEncoding("UTF-8");

        ContextKit.setRequest(request);
        ContextKit.setResponse(response);

        String from = request.getHeader(JwtKit.FROM);
        if (StrUtil.isEmpty(from)) {
            ContextKit.setFrom(Const.from.BIZ);
        } else {
            ContextKit.setFrom(Const.from.valueOf(from.toUpperCase()));
        }


        filterChain.doFilter(servletRequest, servletResponse);
    }
}
